﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using Telerik.Web.UI;
using System.Text;

namespace PEXAM.Admin.Page_Admin
{
    public partial class OperatorPermission : System.Web.UI.Page
    {
        string sErr = "";
        string _strTableName = "data";

        protected void Page_Load(object sender, EventArgs e)
        {


            if (!IsPostBack)
            {                
                LoadGroupCbo();
                if (Session["POGCode"] != null)
                {
                    cboPOG.SelectedValue = Session["POGCode"].ToString();
                }
                else
                    cboPOG.SelectedIndex = 0;
                cboPOG_SelectedIndexChanged(null, null);
            }

        }
        private void LoadGroupCbo()
        {
            BUS.POGControl ctr = new BUS.POGControl();
            DataTable dt = ctr.GetAll(ref sErr);
            cboPOG.DataSource = dt;
            cboPOG.DataTextField = "ROLE_ID";
            cboPOG.DataValueField = "ROLE_ID";
            cboPOG.DataBind();
        }





        private DTO.POPInfo GetDataFromForm()
        {
            DTO.POPInfo result = new DTO.POPInfo();
            result.ROLE_ID = cboPOG.Text;
            result.DEFAULT_VALUE = txtDefault.Text;
            result.DB = txtDB.Text;
            result.PERMISSION = GetPermission((DataTable)Session[_strTableName]);
            return result;
        }

        private void SetDataToForm(DTO.POPInfo objEntr)
        {
            //txtDB.Text = objEntr.DB;
            cboPOG.Text = objEntr.ROLE_ID;
            txtDefault.Text = objEntr.DEFAULT_VALUE;
            hdPermission.Value = objEntr.PERMISSION;
            Session[_strTableName] = LoadDataGrid(objEntr.PERMISSION);
            dgvList.Rebind();
        }


        private string GetPermission(DataTable dt)
        {
            string permission = "";
            foreach (DataRow row in dt.Rows)
            {
                string tmp = row["Permission"].ToString().Trim();
                if (tmp != "Y" && tmp != "N")
                    tmp = " ";
                permission += tmp;
            }
            return permission;
        }
        private DataTable LoadDataGrid(string permission)
        {
            DataTable dt = new DataTable("POP");
            DataColumn[] columns = new DataColumn[] { 
                new DataColumn("ID"), 
                new DataColumn("Module"), 
                new DataColumn("Function"), 
                new DataColumn("Action"), 
                new DataColumn("Permission") 
            };
            dt.Columns.AddRange(columns);
            string fileName = MapPath("~/Admin/Security.xml");
            dt.ReadXml(fileName);
            if (permission.Length >= dt.Rows.Count)
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    dt.Rows[i]["Permission"] = permission.Substring(i, 1);
                }
            return dt;
        }



        protected void dgvList_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            if (Session[_strTableName] != null)
                dgvList.DataSource = (DataTable)Session[_strTableName];
        }

        protected void dgvList_UpdateCommand(object source, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            //Set new values
            Hashtable newValues = new Hashtable();
            //The GridTableView will fill the values from all editable columns in the hash
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
            string id = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString().Trim();

            DataTable dt = (DataTable)Session[_strTableName];
            string keySearch = "ID='" + id + "'";
            DataRow[] rows = dt.Select(keySearch);

            foreach (DictionaryEntry entry in newValues)
            {
                if (entry.Value == null)
                    rows[0][(string)entry.Key] = " ";
                else
                {
                    string tmp = entry.Value.ToString() == "Y" ? "Y" : "N";
                    rows[0][(string)entry.Key] = tmp;
                }
            }
            Session[_strTableName] = dt;
            dgvList.Rebind();
        }

        protected void dgvList_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                try
                {
                    DataRow row = ((DataRowView)e.Item.DataItem).Row;
                    row["Permission"] = row["Permission"].ToString().Trim();
                }
                catch (Exception ex)
                {
                }
            }
        }

        protected void cboPOG_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            BUS.POPControl control = new BUS.POPControl();
            DTO.POPInfo info = control.Get(cboPOG.Text, txtDB.Text, ref sErr);
            SetDataToForm(info);
            Session[_strTableName] = LoadDataGrid(info.PERMISSION);
            dgvList.Rebind();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            DTO.POPInfo info = GetDataFromForm();
            BUS.POPControl control = new BUS.POPControl();
            if (!control.IsExist(info.ROLE_ID, info.DB))
            {
                control.Add(info, ref sErr);
            }
            else
                sErr = control.Update(info);
            if (sErr == "")
            {
                lbErr.Text = "Update successful";
            }
            else
            { lbErr.Text = sErr; }
        }
    }
}
